var serialport = function (name,bit,callback,callopen){
    var comname=name || "COM2";
    var combit=parseInt(bit) || 9600;
    // var comout=parseInt(userArr[3]) || "Hi config";
    var onGetDevices = function(ports) {
        for (var i = 0; i < ports.length; i++) {
            console.log('串口设备:',ports[i].path);
        }
    }
    chrome.serial.getDevices(onGetDevices);

    // var iconv = require('iconv-lite');//若传输英文字符串则无需转码，此处注释掉
    // function convertArrayBufferToString(buf) {//将串口接收到的buffer数据转化成字符串
    //     var bufView = new Uint8Array(buf);
    //     var encodedString = String.fromCharCode.apply(null, bufView);
    //     // document.write(iconv.decode(encodedString, 'gbk'));
    //     //nodejs转编码(不可直接转utf-8否则乱码)//若传输英文字符串则无需转码，此处直接返回
    //     // return iconv.decode(encodedString, 'gbk');
    //     return encodedString;
    // }
    // var convertStringToArrayBuffer = function(str) {//将字符串转化成buffer用于串口数据发送
    //     var buf = new ArrayBuffer(str.length);// (str.length+1)增加一位来放回车符
    //     var bufView = new Uint8Array(buf);
    //     for (var i = 0; i < str.length; i++) {
    //         bufView[i] = str.charCodeAt(i);
    //     }
    //     // bufView[str.length] = 13;//最后一位为回车符的ascii码
    //     return buf;
    // };
    // //convertStringToArrayBuffer('hello')

    function buf2hex(buffer, space) { // buffer is an ArrayBuffer
        return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(space);
    }
    
    function hex2buf(key, space) {
        key = '0x' + key.replace(new RegExp(space, 'g'), ',0x');
        return new Uint8Array(key.split(",")).buffer;
    }
    

    var onReceiveCallback = function(info) {//串口数据接收函数
        var hex=buf2hex(info.data);
        // document.body.insertAdjacentHTML('beforeEnd',"<br>"+code);
        callback && callback(info.data, hex);
    };

    var connectionId;
    var onConnect = function(connectionInfo) {
        if(typeof(connectionInfo)=="undefined"){
            alert("串口连接错误,请选择其他串口");
            return;
        }
        callopen && callopen(connectionInfo);
        console.log('连接信息',chrome.runtime.lastError, connectionInfo);

        chrome.serial.onReceive.addListener(onReceiveCallback);

        connectionId = connectionInfo.connectionId;

        var buffer = new ArrayBuffer(1);
        var dataView = new DataView(buffer);
        // dataView.setInt8(0, 0xaa);

        chrome.serial.send(connectionId, buffer, function() {

            chrome.serial.update(connectionId, {
                bitrate: combit
            }, function(result) {
                console.log(chrome.runtime.lastError, result);
                //发送数据
                chrome.serial.send(connectionId, buffer, console.log.bind(console));

            });

        });
    };

    chrome.serial.connect(comname, {
        bitrate: combit//波特率
    }, onConnect);

    return {
        //发送数据事件
        send: function(str, code){
            // var buffer = new ArrayBuffer(str);
            //发送数据
            if(!code || code=='hex'){
                chrome.serial.send(connectionId, Buffer.from(str.replace(/-+|\s+/g,""), "hex"), console.log.bind(console));
            }else{
                chrome.serial.send(connectionId, Buffer.from(str, code), console.log.bind(console));
            }
            

        }
    }
}
